package array;

import java.util.Arrays;

/**
 * leet-code(238) 除自身以外数组的乘积
 *
 * @author Ringo
 * @date 2021/8/28 20:36
 */
public class ProductExceptSelf {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        System.out.println(Arrays.toString(productExceptSelf(nums)));
    }

    public static int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length == 0)
            return null;
        int n = nums.length;

        // 从左向右遍历
        // left[i] 表示 i 左边数的乘积
        int[] left = new int[n];
        left[0] = 1;
        for (int i = 1; i < n; ++i) {
            left[i] = left[i - 1] * nums[i - 1];
        }

        // 从右向左遍历
        // right[i] 表示 i 右边数的的乘积
        int[] right = new int[n];
        right[n - 1] = 1;
        for (int i = n - 2; i >= 0; --i) {
            right[i] = right[i + 1] * nums[i + 1];
        }

        // 合并结果
        int[] ans = new int[n];
        for (int i = 0; i < n; ++i) {
            ans[i] = left[i] * right[i];
        }

        return ans;
    }

}
